#!/usr/bin/python
# adds a tag to a file
# Usage
# tag.py filename tag1 tag2 tag3 tag4
# what happens if i have 2 files with the same name
# and the same tags like readme.txt
# md5 may solve this problem
# i may md5fy the fullpath which is shorter than the file it self
# may be here i should check for colissions
# colission= two  files with the same name and same tags
import os
import sys
import hashlib

#home = os.getenv("HOME")
#taggerDir = home + '/.tagger/'
taggerDir = os.path.expanduser('~/.tagger')

#dataFile = home + '/.tagger/dic'
dataFile = os.path.expanduser('~/.tagger/dic')
db = open(dataFile,'r')
dataBase = eval(db.read())
db.close()

def tagCount(tag):
   if dataBase.has_key(tag):
      dataBase[tag] = dataBase[tag]+1
   else:
      dataBase[tag] = 1

def addTag(dirname,filename,tag):
   finalDir = os.path.join(taggerDir,tag)
   if not os.path.exists(finalDir):
      os.mkdir(finalDir)

   fullpath = os.path.join(dirname,filename)
   m = hashlib.md5()

   #this code uses the fullpath which should also be unique
   print fullpath
   m.update(fullpath)
   md5str=m.hexdigest()
 
   fullFinalPath = os.path.join(finalDir,md5str)
   os.chdir(finalDir)
   print fullFinalPath
   if not os.path.exists(fullFinalPath):
      try:
	 os.symlink(fullpath,md5str)
      except OSError:
	 print "Links exits?" #somehow the abovecheck fails
      tagCount(tag)

#obtain a string representing the current working directory
cwd = os.getcwd()
pos = sys.argv.index("-")
tags=sys.argv[pos+1:]
for _file in sys.argv[1:pos]:
   print "Tagging "+_file
   #obtain the absolute path to _file
   absPath=os.path.abspath(_file)
   #then, get the base name
   baseName = os.path.basename(absPath)
   #and the dir part of the fullpath
   dirName = os.path.dirname(absPath)

   for tag in tags:
      addTag(dirName,baseName,tag)

   #we have the .all tag always
   addTag(dirName,baseName,".all")

os.chdir(cwd)

db = open(dataFile,'w')
db.write(str(dataBase))
db.close()
